package com.sdry.web.controller.zc;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.sdry.model.barCodeOperation.BarCodeOperation;
import com.sdry.model.jyy.TrayLocation;
import com.sdry.model.lz.CodeMark;
import com.sdry.model.lz.Materiel;
import com.sdry.model.lz.ReceiveMark;
import com.sdry.model.lz.WarehouseRegion;
import com.sdry.model.lz.WarehouseRegionLocation;
import com.sdry.model.zc.ZcMaterielAndTrayEntity;
import com.sdry.model.zc.ZcMaterileMoveInfoEntity;
import com.sdry.model.zc.ZcSysUserEntity;
import com.sdry.model.zc.ZcTrayAndLocationEntity;
import com.sdry.service.barCodeOperation.BarCodeOperationService;
import com.sdry.service.jyy.ReceiveDetailService;
import com.sdry.service.llm.CancellingStockDetailService;
import com.sdry.service.lz.CustomerService;
import com.sdry.service.lz.InventoryService;
import com.sdry.service.prepare.PrepareOneService;
import com.sdry.service.zc.ZcBindAndUnbindService;
import com.sdry.utils.BaseUtils;
import com.sdry.utils.DateUtil;
import com.sdry.utils.ResponseUtil;

/**
 * 
 * @ClassName:    ZcBindAndUnbindController   
 * @Description:  物料与托盘的绑定与解绑        
 * 1.多仓库修改  t  2019-11-01 
	78-81	声明一个Logger
	260-266	APP根据物料条码查询物料信息添加接收仓库id（上架）
	270-274	修改根据条码+","查询库区编号加条件仓库id
 * 2.多仓库修改  t  2019-11-04 
	284-288	根据条码+","、仓库查询库区编号查询物料信息
	301-305	根据条码和仓库id查询同一物料同一批次的所有条码 
	460-482	通过物料条码和仓库id查询物料所在位置(下架)；扫码查询物料位置（下架2）
 * 3.多仓库修改  t  2019-11-05
	667-669	添加仓库id注释
	675-677	上架提交时添加接收仓库id
	679-684	上架提交时参数logger提示
	689-694	通过物料条码和仓库id查询物料所在位置 以托盘为主
	720-733	给上架方法传送参数的logger提示；传送参数添加仓库id
	754-757	给操作记录添加仓库id
	773-790	上架方法接收参数添加仓库id，加注释
	794-799	根据库位码和仓库id查询在良品区的条数
	806-811	根据库位码和仓库id查询在不良品区的条数
	834-838	调用server区域库存的移动添加参数仓库id
 * 4.多仓库修改  t  2019-11-06
	115-121  从session获取仓库id,根据条码+","、仓库查询物料信息
 * @Author:       zc   
 * @CreateDate:   2019年6月3日 上午9:22:20   
 * @Version:      v1.0
 */
@Controller
@RequestMapping("bindAndUnbind")
public class ZcBindAndUnbindController {
	
	/* ******************************多仓库修改  t  2019-11-01 开始*************************** */
	//声明一个Logger
	private final static Logger logger = LoggerFactory.getLogger(ZcBindAndUnbindController.class);
	/* ******************************多仓库修改  t  2019-11-01 结束*************************** */
	
	 @Resource
	 CustomerService  customerService;
	@Resource
	private ZcBindAndUnbindService zcBindAndUnbindService;
	@Resource
	private BarCodeOperationService barCodeOperationService;
	@Resource
	private PrepareOneService prepareOneService;
	@Resource
	private ReceiveDetailService ReceiveDetailService;
	@Resource
	private InventoryService inventoryService;
	@Resource
	private CancellingStockDetailService cancellingStockDetailService;
	
	/**
	 * 进入绑定与解绑页面
	 * @return
	 */
	@RequestMapping("enterBindAndUnbindPage")
	public ModelAndView enterBindAndUnbindPage(){
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/zc/warehouse/bindAndUnbind");
		return mav;
	}
	/**
	 * 通过物料条码查询物料信息
	 * @param materiel_code
	 * @param response
	 */
	@RequestMapping("selectMaterielInfoByCode")
	public void selectMaterielInfoByCode(String materiel_code,
			HttpServletResponse response, HttpSession httpSession) {
		logger.info("bindAndUnbind/selectMaterielInfoByCode.do通过物料条码查询物料信息接收参数：materiel_code = "+materiel_code);
		/* ******************************多仓库修改  t  2019-11-01 开始*************************** */
		//从session获取仓库id（仓库id有可能为空）
		Long warehouse_id = (Long) httpSession.getAttribute("warehouse_id");
		logger.info("通过物料条码查询物料信息session获取仓库id：warehouse_id = "+warehouse_id);
		//根据条码+","、仓库查询物料信息
		Materiel materiel = zcBindAndUnbindService.selectMaterielInfoByCode(materiel_code,warehouse_id);
		logger.info("通过物料条码查询物料信息查询出的物料信息：materiel = "+materiel.toString());
		//多仓库修改之前：Materiel materiel = zcBindAndUnbindService.selectMaterielInfoByCode(materiel_code);
		/* ******************************多仓库修改  t  2019-11-01 结束*************************** */
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("data", materiel);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			logger.info("通过物料条码查询物料信息传送数据失败");
			e.printStackTrace();
		}
	}
	/**
	 * 绑定物料托盘并上架
	 * @param httpSession
	 * @param response
	 * @param zcMaterielAndTrayEntity
	 */
	@RequestMapping("bindingAndUp")
	public void bindingAndUp(HttpSession httpSession,
			HttpServletResponse response,
			ZcMaterielAndTrayEntity zcMaterielAndTrayEntity) {
		logger.info("bindAndUnbind/bindingAndUp.do绑定物料托盘并上架接收参数：zcMaterielAndTrayEntity = "+zcMaterielAndTrayEntity.toString());
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
		zcMaterielAndTrayEntity.setBinding_person(su.getId());
		zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
		/* ******************************多仓库修改  t  2019-11-07 开始*************************** */
		//从session获取仓库id（仓库id有可能为空）        ：
		Long warehouse_id = (Long) httpSession.getAttribute("warehouse_id");
		logger.info("绑定物料托盘并上架session获取仓库id：warehouse_id = "+warehouse_id);
		zcMaterielAndTrayEntity.setWarehouse_id(warehouse_id);
		/* ******************************多仓库修改  t  2019-11-07 开始*************************** */
		int affact = zcBindAndUnbindService.bindingAndUp(zcMaterielAndTrayEntity);
		logger.info("绑定物料托盘并上架zcBindAndUnbindService.bindingAndUp返回值"+affact);
		try {
			ResponseUtil.write(response, affact);
		} catch (Exception e) {
			logger.info("绑定物料托盘并上架传送数据失败");
			e.printStackTrace();
		}
	}
	/**
	 * 通过物料条码查询物料所在位置及库位详情
	 */
	@RequestMapping("selectMaterielLocationByCode")
	public void selectMaterielLocationByCode(String materiel_code,HttpServletResponse response){
		logger.info("bindAndUnbind/selectMaterielLocationByCode.do通过物料条码查询物料所在位置及库位详情接收参数：materiel_code = "
				+ materiel_code);
		//通过物料条码查询物料所在位置
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService
				.selectMaterielLocationByCode(materiel_code);
		logger.info("通过物料条码查询物料所在位置及库位详情：zcMaterielAndTrayEntity = "
				+ zcMaterielAndTrayEntity.toString());
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("data", zcMaterielAndTrayEntity);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			logger.info("通过物料条码查询物料所在位置及库位详情传送数据失败");
			e.printStackTrace();
		}
	}
	/**
	 * 下架解绑物料托盘
	 * @param httpSession
	 * @param response
	 * @param zcMaterielAndTrayEntity
	 */
	@RequestMapping("downAndUnbind")
	public void downAndUnbind(HttpSession httpSession,
			HttpServletResponse response,
			ZcMaterielAndTrayEntity zcMaterielAndTrayEntity) {
		logger.info("bindAndUnbind/downAndUnbind.do下架解绑物料托盘接收参数：zcMaterielAndTrayEntity = "+zcMaterielAndTrayEntity.toString());
		/* ******************************多仓库修改  t  2019-11-07 开始*************************** */
		//从session获取仓库id（仓库id有可能为空）        ：
		Long warehouse_id = (Long) httpSession.getAttribute("warehouse_id");
		logger.info("下架解绑物料托盘session获取仓库id：warehouse_id = "+warehouse_id);
		zcMaterielAndTrayEntity.setWarehouse_id(warehouse_id);
		/* ******************************多仓库修改  t  2019-11-07 开始*************************** */
		int affact = zcBindAndUnbindService.downAndUnbind(zcMaterielAndTrayEntity);
		logger.info("下架解绑物料托盘返回值："+affact);
		try {
			ResponseUtil.write(response, affact);
		} catch (Exception e) {
			logger.info("下架解绑物料托盘传送数据失败");
			e.printStackTrace();
		}
	}
	/**
	 * 条件查询库位信息
	 * @param materiel
	 */
	@RequestMapping("selectTopLocation")
	public void selectTopLocation(Materiel materiel, HttpServletResponse response){
		logger.info("bindAndUnbind/selectTopLocation.do条件查询库位信息接收参数：materiel = "+materiel.toString());
		if(materiel.getMateriel_num()==null){
			materiel.setMateriel_num("");
		}
		if(materiel.getMateriel_size()==null){
			materiel.setMateriel_size("");
		}
		if(materiel.getMateriel_properties()==null){
			materiel.setMateriel_properties("");
		}
		List<WarehouseRegionLocation> warehouseRegionLocation = zcBindAndUnbindService.selectTopLocation(materiel);
		logger.info("条件查询库位信息返回数据：List<WarehouseRegionLocation> = "
				+ warehouseRegionLocation.toString());
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(warehouseRegionLocation, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			logger.info("条件查询库位信息返回数据传送数据失败");
			e.printStackTrace();
		}
	}

	/**
	 * 代码优化后，多仓库版本
	 * @return modelAndView
	 */
	@RequestMapping(value = "enterLocationRealtimeInfoPage")
	public ModelAndView enterLocationRealtimeInfoPage() {
		ModelAndView modelAndView = new ModelAndView();
		//大库区
		List<WarehouseRegion> allRegion = zcBindAndUnbindService
				.selectAllRegion(BaseUtils.getSession());
		modelAndView.addObject("allRegion", allRegion);
		modelAndView.setViewName("zc/warehouse/locationRealtimeInfo_wareHouseId");
		return modelAndView;
	}

	/**
	 * 库区id
	 * @param regionId
	 */
	@RequestMapping(value = "getRegionDetailByRegionId")
	@ResponseBody
	public List<WarehouseRegionLocation> getRegionDetailByRegionId(Long regionId) {
		List<WarehouseRegionLocation> byRegionId = zcBindAndUnbindService.getRegionDetailByRegionId(regionId);
		return byRegionId;
	}

	/**
	 * 点击条码的详细信息
	 * @param location_num
	 * @return
	 */
	@RequestMapping(value = "regionDetailPage")
	public String regionDetailPage(String location_num,Model model) {
		WarehouseRegionLocation warehouseRegionLocation = zcBindAndUnbindService
				.getRegionDetail(location_num);
		List<Materiel> materielList = zcBindAndUnbindService.getMaterielList(location_num);
		model.addAttribute("warehouseRegionLocation", warehouseRegionLocation);
		model.addAttribute("materielList", materielList);
		return "zc/warehouse/regionDetailPage";
	}


	/**
	 * 进入库位实时信息页面
	 */
	/*@RequestMapping("enterLocationRealtimeInfoPage")
	public ModelAndView enterLocationRealtimeInfoPage(Materiel materiel,
			Model model, HttpSession session, HttpServletResponse response) {
		long t1=System.currentTimeMillis();
		logger.info("bindAndUnbind/enterLocationRealtimeInfoPage.do进入库位实时信息页面接收参数：materiel = "
				+ materiel.toString());
		ZcSysUserEntity staf = (ZcSysUserEntity) session.getAttribute("user");
		Long warehouse_id = (Long) session.getAttribute("warehouse_id");
		if (materiel.getMateriel_num() == null) {
			materiel.setMateriel_num("");
		}
		if (materiel.getMateriel_size() == null) {
			materiel.setMateriel_size("");
		}
		if (materiel.getMateriel_properties() == null) {
			materiel.setMateriel_properties("");
		}

		//如果是客户登录
		if (staf.getRoleId().equals("20010,")) {

			//查询库位信息
			List<WarehouseRegionLocation> warehouseRegionLocation = zcBindAndUnbindService
					.selectTopLocation(materiel);

			List<WarehouseRegion> allRegion = zcBindAndUnbindService
					.selectAllRegion(warehouse_id);

			ModelAndView mav = new ModelAndView();
			Customer customer = customerService.queryCustomerlxrById(staf
					.getCustomer_id());

			model.addAttribute("cname", customer.getCustomer_name());
			model.addAttribute("cid", staf.getCustomer_id());
			model.addAttribute("sid", staf.getCustomer_id());
			mav.addObject("warehouseRegionLocation", warehouseRegionLocation);
			mav.addObject("allRegion", allRegion);
			mav.setViewName("zc/warehouse/locationRealtimeInfo2");
			return mav;
		} else {

			long t3=System.currentTimeMillis();
			List<WarehouseRegionLocation> warehouseRegionLocation = zcBindAndUnbindService
					.selectTopLocation(materiel);
			long t4=System.currentTimeMillis();

			long t5=System.currentTimeMillis();
			List<WarehouseRegion> allRegion = zcBindAndUnbindService
					.selectAllRegion(warehouse_id);
			long t6=System.currentTimeMillis();
			ModelAndView mav = new ModelAndView();
			mav.addObject("warehouseRegionLocation", warehouseRegionLocation);
			mav.addObject("allRegion", allRegion);
			mav.setViewName("zc/warehouse/locationRealtimeInfo");
			long t2=System.currentTimeMillis();
			System.out.println("进入库位实时信息页面，开始时间，单位毫秒t1="+t1);
			System.out.println("进入库位实时信息页面，结束时间，单位毫秒t2="+t2);
			System.out.println("t3="+t3);
			System.out.println("t4="+t4);
			System.out.println("t5="+t5);
			System.out.println("t6="+t6);
			System.out.println("整体运行时间，单位毫秒，t2-t1="+(t2-t1));
			System.out.println("warehouseRegionLocation 方法运行时间，单位毫秒t4-t3="+(t4-t3));
			System.out.println("allRegion 方法运行时间，单位毫秒 t6-t5="+(t6-t5));
			return mav;
		}
	}*/
	/*******************************************APP************************************************/
	/**
	 * 通过物料条码查询物料信息
	 * @param materiel_code
	 * @param response
	 */
	@RequestMapping("selectMaterielInfoByCodeAppZc")
	/* ******************************多仓库修改  t  2019-11-01 开始*************************** */
	//多仓库修改之前：public void selectMaterielInfoByCodeApp(HttpServletResponse response,String materiel_code){
	//添加接收仓库id
	public void selectMaterielInfoByCodeAppZc(Long warehouse_id,HttpServletResponse response,String materiel_code){
		//日志
		logger.info("bindAndUnbind/selectMaterielInfoByCodeApp.do（上架）根据物料条码查询物料信息接收参数：warehouse_id="
				+ warehouse_id + ",materiel_code=" + materiel_code);
	/* ******************************多仓库修改  t  2019-11-01 结束*************************** */
		JSONObject jsonObject = new JSONObject();
		String return_code=materiel_code;
		materiel_code += ",";
		/* ******************************多仓库修改  t  2019-11-01 开始*************************** */
		//根据条码+","、仓库查询库区编号
		String location_code = zcBindAndUnbindService.selectByMaterielCode(materiel_code,warehouse_id);
		logger.info("（上架）根据物料条码查询物料信息查询库位：location_code=" + location_code);
		//多仓库修改之前：String location_code = zcBindAndUnbindService.selectByMaterielCode(materiel_code);
		/* ******************************多仓库修改  t  2019-11-01 结束*************************** */
		if("SY".equals(location_code)){
			jsonObject.put("status", "0");
			jsonObject.put("message", "该条码在损溢区");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				logger.info("（上架）根据物料条码查询物料信息传送数据失败");
				e.printStackTrace();
			}
		}else{
			/* ******************************多仓库修改  t  2019-11-04 开始*************************** */
			//根据条码+","、仓库查询库区编号查询物料信息
			Materiel materiel = zcBindAndUnbindService.selectMaterielInfoByCode(materiel_code,warehouse_id);
			//多仓库修改之前：Materiel materiel = zcBindAndUnbindService.selectMaterielInfoByCode(materiel_code);
			/* ******************************多仓库修改  t  2019-11-04 结束*************************** */
			if((materiel == null) || (materiel.getId() == null)){
				/*jsonObject.put("status", "0");
				jsonObject.put("message", "查询不到此条码");*/
				/*codemark表中无此条码
				1.先在条码记录表中查询有没有，有，则表示此条码已出库。
				2.没有，就在receivemark表中查询，有，则表示，条码未收货，没有，表示系统无此条码*/
				
				//根据条码在条码记录表中查询此条码的信息
				BarCodeOperation param = new BarCodeOperation();
				param.setBarCode(return_code);
				List<BarCodeOperation> list = barCodeOperationService.queryAllByMution(param);
				
				if(list.size() > 0) {
					param.setWarehouse_id(warehouse_id);
					//根据条码和仓库id在操作记录表中查询此条码,存在，条码已出库，不存在，条码在别的仓库
					List<BarCodeOperation> list2 = barCodeOperationService.queryAllByMution(param);
					
					if(list2.size() > 0) {
						//此条码已出库
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "条码已出库或已拆箱");
						jsonObject.put("data", null);
					}else {
						//此条码已出库
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "该条码不属于本仓库");
						jsonObject.put("data", null);
					}
				}else {
					
					//根据条码，在receivemark表中查询
					ReceiveMark receiveMark = ReceiveDetailService.selectReceiveMarkByCode(return_code);
					
					if(receiveMark != null) {
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "条码未收货，收货单号："+receiveMark.getReceiveDetail().getReceiveNumber());
						jsonObject.put("data", null);
					}else {
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "系统无此条码");
						jsonObject.put("data", null);
					}
					
				}
				try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					logger.info("（上架）根据物料条码查询物料信息传送数据失败");
					e.printStackTrace();
				}
			} else {
				//llm 查询同一物料同一批次的所有条码
				int count = 0;
				String code = materiel_code.replace(",", "");
				/* ******************************多仓库修改  t  2019-11-04 开始*************************** */
				//根据条码和仓库id查询同一物料同一批次的所有条码 
				List<CodeMark> codes = barCodeOperationService.selectCountOnSameCodeByCode(code,warehouse_id);
				//多仓库修改之前：List<CodeMark> codes = barCodeOperationService.selectCountOnSameCodeByCode(code);
				/* ******************************多仓库修改  t  2019-11-04 结束*************************** */
				for(CodeMark codeMark : codes){
					//String location = zcBindAndUnbindService.selectByMaterielCode(codeMark.getCode() + ",");
					if("DJ".equals(codeMark.getLocation_name()) || "HC".equals(codeMark.getLocation_name())){
						count += 1;
					}
				}
				if(location_code!= null && !"DJ".equals(location_code) && !"HC".equals(location_code)){
					jsonObject.put("status", "0");
					jsonObject.put("message", "此条码已上架");
					try {
						ResponseUtil.write(response, jsonObject);
					} catch (Exception e) {
						e.printStackTrace();
					}
					return;
				}else{
					Integer i = barCodeOperationService.queryStatusByCode(code);
					if(i == null){
						i = 0;
					}
					if(i == 0){
						jsonObject.put("status", "0");
						jsonObject.put("message", "此条码未质检");
						try {
							ResponseUtil.write(response, jsonObject);
						} catch (Exception e) {
							e.printStackTrace();
						}
						return;
					}
				}
				jsonObject.put("status", "1");
				jsonObject.put("data", materiel.getIs_bindtray()+","+materiel.getBetter_location()+","+materiel.getId()+materiel.getPici()+","+count+","+return_code);
				try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					logger.info("（上架）根据物料条码查询物料信息传送数据失败");
					e.printStackTrace();
				}
			}
		}
	}
	
	
	/**
	 * 绑定物料托盘并上架
	 * @param response
	 * @param materiel_code 物料精确码，多个用逗号隔开
	 * @param tray_code	托盘码
	 * @param binding_person 绑定人id
	 * ******************************多仓库修改  t  2019-11-06 开始*************************** 
	 * @param warehouse_id 仓库id
	 * ******************************多仓库修改  t  2019-11-06 结束*************************** 
	 */
	@RequestMapping("bindingMaterielAndTrayApp")
	public void bindingMaterielAndTrayApp(HttpServletResponse response,
			String materiel_code, String tray_code, String location_code,
			String binding_person
			/*******************************多仓库修改  t  2019-11-06 开始*************************** */
			//接收仓库id
			,Long warehouse_id
			/*******************************多仓库修改  t  2019-11-06 结束*************************** */
			) {
		logger.info("bindAndUnbind/bindingMaterielAndTrayApp.do绑定物料托盘并上架接收参数：materiel_code="
				+ materiel_code
				+ ",tray_code="
				+ tray_code
				+ ",location_code="
				+ location_code
				+ ",binding_person="
				+ binding_person
				+ ",warehouse_id=" + warehouse_id);
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
		/*******************************多仓库修改  t  2019-11-06 开始*************************** */
		//根据条码+","、仓库查询物料信息
		Materiel materiel = zcBindAndUnbindService.selectMaterielInfoByCode(materiel_code,warehouse_id);
		//多仓库修改之前：Materiel materiel = zcBindAndUnbindService.selectMaterielInfoByCode(materiel_code);
		/*******************************多仓库修改  t  2019-11-06 结束*************************** */
		zcMaterielAndTrayEntity.setMateriel_code(materiel_code);
		zcMaterielAndTrayEntity.setTray_code(tray_code);
		zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(binding_person));
		zcMaterielAndTrayEntity.setLocation_code(location_code);
		zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
		zcMaterielAndTrayEntity.setMid(materiel.getId());
		zcMaterielAndTrayEntity.setmBatch(materiel.getPici());
		zcMaterielAndTrayEntity.setIs_ng(materiel.getIs_ng());
		/* ******************************多仓库修改  t  2019-11-07 开始*************************** */
		//给zcMaterielAndTrayEntity添加warehouse_id
		zcMaterielAndTrayEntity.setWarehouse_id(warehouse_id);
		/* ******************************多仓库修改  t  2019-11-07 结束*************************** */
		logger.info("绑定物料托盘并上架zcBindAndUnbindService.bindingAndUp传送参数：zcMaterielAndTrayEntity="
				+ zcMaterielAndTrayEntity.toString());
		int affact = zcBindAndUnbindService.bindingAndUp(zcMaterielAndTrayEntity);
		logger.info("绑定物料托盘并上架zcBindAndUnbindService.bindingAndUp返回值："+ affact);
		JSONObject jsonObject = new JSONObject();
		if(affact > 0){
            jsonObject.put("status", "1");
            jsonObject.put("data", "提交成功");
        } else if(affact == -2) {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败，请绑定同一种物料");
        } else if(affact == -3) {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败，物料已经上架");
        } else if(affact == -4) {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败，此物料不能上架");
        } else if(affact == -5) {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败，此物料不能上架到此库区");
        } else if(affact == -6) {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败,此物料为不良品，请上架到不良品区");
        }else {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败");
        }
		//传送数据
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			logger.info("绑定物料托盘并上架传送数据失败");
			e.printStackTrace();
		}
	}
	/**
	 * 通过物料条码查询物料所在位置
	 */
	@RequestMapping("selectMaterielLocationByCodeApp")
	public void selectMaterielLocationByCodeApp(String materiel_code,HttpServletResponse response){
		logger.info("bindAndUnbind/selectMaterielLocationByCodeApp.do通过物料条码查询物料所在位置接收参数：materiel_code=" + materiel_code);
		materiel_code+=",";
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielLocationByCode(materiel_code);
		logger.info("通过物料条码查询物料所在位置传送返回数据zcMaterielAndTrayEntity="+zcMaterielAndTrayEntity);
		JSONObject jsonObject = new JSONObject();
		if(null == zcMaterielAndTrayEntity){
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询不到此物料");
		}else{
			jsonObject.put("status", "1");
			jsonObject.put("data", zcMaterielAndTrayEntity);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			logger.info("通过物料条码查询物料所在位置传送数据失败");
			e.printStackTrace();
		}
	}
	/* ******************************多仓库修改  t  2019-11-04 开始*************************** */
	//多仓库修改之前：
	/**
	 * 通过物料条码查询物料所在位置(下架)
	 *//*
	@RequestMapping("selectMaterielLocationByCodeAppDown")
	public void selectMaterielLocationByCodeAppDown(String materiel_code,HttpServletResponse response){*/
		/*String materiel_code_single = materiel_code;
			//materiel_code+=",";
			ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielLocationByCodeDown1(materiel_code);*/
	/**
	 * 通过物料条码和仓库id查询物料所在位置(下架)
	 * @param materiel_code 条码
	 * @param warehouse_id 仓库id
	 * @param response
	 */
	@RequestMapping("selectMaterielLocationByCodeAppDownLlm")
	public void selectMaterielLocationByCodeAppDownLlm(String materiel_code,Long warehouse_id,HttpServletResponse response){
		//日志
		logger.info("bindAndUnbind/selectMaterielLocationByCodeAppDown.do（下架）根据物料条码和仓库id查询物料所在位置接收参数：materiel_code="+materiel_code+",warehouse_id="+warehouse_id);
		String materiel_code_single = materiel_code;
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielLocationByCodeDown1(materiel_code,warehouse_id);
		logger.info("通过物料条码和仓库id查询物料所在位置(下架)查询出的数据zcMaterielAndTrayEntity="+zcMaterielAndTrayEntity.toString());
		/* ******************************多仓库修改  t  2019-11-04 结束*************************** */
		JSONObject jsonObject = new JSONObject();
		if(null == zcMaterielAndTrayEntity || null == zcMaterielAndTrayEntity.getLocation_code() || "".equals(zcMaterielAndTrayEntity.getLocation_code())){
			/*jsonObject.put("status", "0");
			jsonObject.put("message", "此条码不存在");*/
			/*codemark表中无此条码
			1.先在条码记录表中查询有没有，有，则表示此条码已出库。
			2.没有，就在receivemark表中查询，有，则表示，条码未收货，没有，表示系统无此条码*/
			
			//根据条码在条码记录表中查询此条码的信息
			BarCodeOperation param = new BarCodeOperation();
			param.setBarCode(materiel_code);
			List<BarCodeOperation> list = barCodeOperationService.queryAllByMution(param);
			
			if(list.size() > 0) {
				
				param.setWarehouse_id(warehouse_id);
				//根据条码和仓库id在操作记录表中查询此条码,存在，条码已出库，不存在，条码在别的仓库
				List<BarCodeOperation> list2 = barCodeOperationService.queryAllByMution(param);
				
				if(list2.size() > 0) {
					//此条码已出库
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "条码已出库或已拆箱");
					jsonObject.put("data", null);
				}else {
					//此条码已出库
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "该条码不属于本仓库");
					jsonObject.put("data", null);
				}
			}else {
				
				//根据条码，在receivemark表中查询
				ReceiveMark receiveMark = ReceiveDetailService.selectReceiveMarkByCode(materiel_code);
				
				if(receiveMark != null) {
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "条码未收货，收货单号："+receiveMark.getReceiveDetail().getReceiveNumber());
					jsonObject.put("data", null);
				}else {
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "系统无此条码");
					jsonObject.put("data", null);
				}
				
			}
		} else if ("HC".equals(zcMaterielAndTrayEntity.getLocation_code())) {
			jsonObject.put("status", "0");
			jsonObject.put("message", "此物料已下架");
		} else if ("DJ".equals(zcMaterielAndTrayEntity.getLocation_code())) {
			jsonObject.put("status", "0");
			jsonObject.put("message", "待上架区不能下架");
		}else if("SY".equals(zcMaterielAndTrayEntity.getLocation_code())){
			jsonObject.put("status", "0");
			jsonObject.put("message", "该条码在损溢区");
		} else {
			Integer down_code_num = prepareOneService.selectCodemarkNumbyCode(materiel_code.replace(",", ""));
			if(down_code_num != null){
				zcMaterielAndTrayEntity.setDown_code_num(down_code_num);
			}
			jsonObject.put("status", "1");
			zcMaterielAndTrayEntity.setMateriel_code_single(materiel_code_single);
			jsonObject.put("data", zcMaterielAndTrayEntity);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			jsonObject.put("status", "0");
			jsonObject.put("message", "下架条码查询错误");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			logger.info("通过物料条码和仓库id查询物料所在位置(下架)传送数据失败");
			e.printStackTrace();
		}
	}
	/* ******************************多仓库修改  t  2019-11-07 开始*************************** */
	/**
	 * 下架解绑物料托盘
	 * @param response
	 * @param location 库位条码
	 * @param tray 托盘条码
	 * @param materiel_code 物料条码
	 * @param unbindle_reason 解绑原因，解绑时用
	 * @param state 下架类型，解绑时用
	 * ******************************多仓库修改  t  2019-11-07 开始***************************
	 * @param warehouse_id 仓库id
	 * ******************************多仓库修改  t  2019-11-07 结束***************************
	 */
	@RequestMapping("unbindMaterielAndTrayApp")
	public void unbindMaterielAndTrayApp(HttpServletResponse response,
			String location, String tray, String materiel_code,
			String unbindle_reason, String state
			/*******************************多仓库修改  t  2019-11-07 开始****************************/
			//添加仓库id的参数
			,Long warehouse_id
			/*******************************多仓库修改  t  2019-11-07 结束****************************/
			) {
		logger.info("bindAndUnbind/unbindMaterielAndTrayApp.do下架解绑物料托盘接收参数：location="
				+ location
				+ ",tray="
				+ tray
				+ "materiel_code="
				+ materiel_code
				+ "unbindle_reason="
				+ unbindle_reason
				+ "state="
				+ state + "warehouse_id=" + warehouse_id);
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
		zcMaterielAndTrayEntity.setMateriel_code(materiel_code);
		zcMaterielAndTrayEntity.setUnbindle_reason(unbindle_reason);
		zcMaterielAndTrayEntity.setTray_code(tray);
		zcMaterielAndTrayEntity.setLocation_code(location);
		zcMaterielAndTrayEntity.setDownType(Integer.parseInt(state));
		/* ******************************多仓库修改  t  2019-11-07 开始*************************** */
		//给zcMaterielAndTrayEntity添加warehouse_id
		zcMaterielAndTrayEntity.setWarehouse_id(warehouse_id);
		/* ******************************多仓库修改  t  2019-11-07 结束*************************** */
		logger.info("下架解绑物料托盘zcBindAndUnbindService.downAndUnbind传送zcMaterielAndTrayEntity="+zcMaterielAndTrayEntity.toString());
		int affact = zcBindAndUnbindService.downAndUnbind(zcMaterielAndTrayEntity);
		JSONObject jsonObject = new JSONObject();
		if(affact > 0){
            jsonObject.put("status", "1");
            jsonObject.put("data", "提交成功");
        }else if(affact == -2) {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败，托盘或物料条码不正确");
        } else {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败");
        }
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			logger.info("下架解绑物料托盘传送数据失败");
			e.printStackTrace();
		}
	}
	
	/**
	 * 区域库存的移动(上架)
	 * @param response
	 * @param downType 下架类型，1全部，2部分
	 * @param materiel_code 物料条码
	 * @param location_code 库位条码
	 * @param tray_code 托盘条码
	 * @param targetRegion 目标区域
	 * @param binding_person 人员id
	 * ******************************多仓库修改  t  2019-11-06 开始*************************** 
	 * @param warehouse_id 仓库id
	 * ******************************多仓库修改  t  2019-11-06 结束*************************** 
	 */
	@RequestMapping("bindAndUp2SpecialAreaUp")
	public void bindAndUp2SpecialAreaUp(HttpServletResponse response,
			String downType, String materiel_code, String location_code,
			String tray_code, String targetRegion, String binding_person
			/*******************************多仓库修改  t  2019-11-06 开始*************************** */
			//接收仓库id
			,Long warehouse_id
			/*******************************多仓库修改  t  2019-11-06 结束*************************** */
			) {
		logger.info("bindAndUnbind/bindAndUp2SpecialAreaUp.do区域库存的移动(上架)接收参数：downType="
				+ downType
				+ ",materiel_code="
				+ materiel_code
				+ "location_code="
				+ location_code
				+ "tray_code="
				+ tray_code
				+ "targetRegion="
				+ targetRegion + "binding_person=" + binding_person + "warehouse_id=" + warehouse_id);
		int affact = 0;
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("message", "提交失败");
		//遍历数组
		String [] codeArr = materiel_code.split(",");
		for (String code : codeArr) {
			List<WarehouseRegionLocation> warehouseRegionLocationList = zcBindAndUnbindService.queryLocationByCode(code);
			for (WarehouseRegionLocation warehouseRegionLocation : warehouseRegionLocationList) {
				//如果匹配上
				if (warehouseRegionLocation.getLocation_num().equals(location_code)) {
					if(downType==null || "".equals(downType)){
						downType= "2";
					}
					Date date = new Date();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
					if(tray_code==null || "".equals(tray_code)){
						tray_code = System.currentTimeMillis()+"";
					}
					zcMaterielAndTrayEntity.setMateriel_code(materiel_code);
					zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(binding_person));
					zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
					zcMaterielAndTrayEntity.setTargetRegion(targetRegion);
					zcMaterielAndTrayEntity.setTray_code(tray_code);
					zcMaterielAndTrayEntity.setLocation_code(location_code);
					zcMaterielAndTrayEntity.setDownType(Integer.parseInt(downType));
					/*******************************多仓库修改  t  2019-11-06 开始*************************** */
					//调用server区域库存的移动添加参数仓库id
					affact = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity,warehouse_id);
					//多仓库修改之前：affact = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity);
					/*******************************多仓库修改  t  2019-11-06 结束*************************** */
					//----------------------给历史记录表插入数据   start-------------------------------------
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String time = format.format(new Date());
					BarCodeOperation bar = new BarCodeOperation();
					bar.setOperator(Long.parseLong(binding_person));
					bar.setOperatingTime(time);
					bar.setBarCode(materiel_code);
					bar.setLocationId(location_code);
					if("良品区".equals(targetRegion) || "不良品区".equals(targetRegion)){
						bar.setType("上架");
					}else{
						bar.setType("下架");
					}
					if(affact > 0){
						bar.setResult("成功");
					}else{
						bar.setResult("失败");
					}
					/* ******************************多仓库修改  t  2019-11-07 开始*************************** */
					//条码操作记录set仓库id
					bar.setWarehouse_id(warehouse_id);
					/* ******************************多仓库修改  t  2019-11-07 结束*************************** */
					barCodeOperationService.insert(bar);
					//----------------------给历史记录表插入数据  end-------------------------------------
				} else {
					affact = -1;
					jsonObject.put("message", "查询不到此库位");
				}
			}
		}
		if(affact <= 0){
        	jsonObject.put("status", "0");
        } else {
        	jsonObject.put("status", "1");
            jsonObject.put("message", "");
            jsonObject.put("data", "提交成功");
        }
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			logger.info("区域库存的移动(上架)传送数据失败");
			e.printStackTrace();
		}
	}
	
	/**
	 * 区域库存的移动（上架）
	 * @param response
	 * @param downType 下架类型，1全部，2部分
	 * @param materiel_code 物料条码
	 * @param location_code 库位条码
	 * @param tray_code 托盘条码
	 * @param targetRegion 目标区域
	 * @param binding_person 人员id
	  ******************************多仓库修改  t  2019-11-05 开始*************************** 
	 * @param warehouse_id 仓库id
	  ******************************多仓库修改  t  2019-11-05 结束*************************** 
	 */
	@RequestMapping("bindAndUp2SpecialArea3ZC")
	public void bindAndUp2SpecialArea3ZC(HttpServletResponse response,
			String downType, String materiel_code, String location_code,
			String tray_code, String targetRegion, String binding_person
			/* ******************************多仓库修改  t  2019-11-05 开始*************************** */
			,Long warehouse_id
			/* ******************************多仓库修改  t  2019-11-05 结束*************************** */
			) {
		/* ******************************多仓库修改  t  2019-11-05 开始*************************** */
		logger.info("bindAndUnbind/bindAndUp2SpecialArea3.do上架操作方法传值：downType=" + downType + ";materiel_code=" + materiel_code
				+ ";location_code=" + location_code + "location_code=" + location_code 
				+ ";tray_code="+ tray_code + ";targetRegion="+ targetRegion
				+ ";binding_person="+ binding_person + ";warehouse_id="+ warehouse_id);
		/* ******************************多仓库修改  t  2019-11-05 结束*************************** */
		JSONObject jsonObject = new JSONObject();
		List<String> listsx = Arrays.asList(materiel_code.split(","));
		List<ZcMaterielAndTrayEntity> list = new ArrayList<>();
		for (String s:listsx){
			/* ******************************多仓库修改  t  2019-11-05 开始*************************** */
			//通过物料条码和仓库id查询物料所在位置 以托盘为主
			ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielTrayLocationByCode(s,warehouse_id);
			//根据条码查询物料托盘绑定信息
			//多仓库修改之前：ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielTrayLocationByCode(s);
			/* ******************************多仓库修改  t  2019-11-05 结束*************************** */
			//获取托盘码
			String tray_code1 = zcMaterielAndTrayEntity.getTray_code();
			int fid = 0;
			for (int i = 0; i < list.size(); i++) {
				if(list.get(i).getTray_code().equals(tray_code1)){
					String Materiel_code = list.get(i).getMateriel_code()+s+",";
					zcMaterielAndTrayEntity.setMateriel_code(Materiel_code);
					list.remove(i);
					list.add(zcMaterielAndTrayEntity);
					fid = 1;
					break;
				}
			}
			if(fid == 0){
				zcMaterielAndTrayEntity.setMateriel_code(s+",");
				list.add(zcMaterielAndTrayEntity);
			}
		}
		
		//SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//String time = format.format(new Date());
		String time = System.currentTimeMillis() + "";
		for (ZcMaterielAndTrayEntity zcMaterielAndTrayEntity:list){
			String s = zcMaterielAndTrayEntity.getMateriel_code();
			//String tray_codes = zcMaterielAndTrayEntity.getTray_code();
			/* ******************************多仓库修改  t  2019-11-05 开始*************************** */
			logger.info("上架操作方法传值：downType=" + downType + ";条码s=" + s
					+ ";location_code=" + location_code + ";time=" + time
					+ "targetRegion=" + targetRegion + ";binding_person="+ binding_person 
					+ ";mid="+ zcMaterielAndTrayEntity.getMid()
					+ ";mBatch="+ zcMaterielAndTrayEntity.getmBatch()
					+ ";warehouse_id="+ warehouse_id);
			//上架操作方法添加仓库id
			jsonObject = bindAndUp2SpecialAreaMethod1(response, downType, s,
					location_code, time, targetRegion, binding_person,
					zcMaterielAndTrayEntity.getMid(),
					zcMaterielAndTrayEntity.getmBatch(), warehouse_id);
			//多仓库修改之前：jsonObject = bindAndUp2SpecialAreaMethod1(response, downType, s, location_code, time, targetRegion, binding_person,zcMaterielAndTrayEntity.getMid(),zcMaterielAndTrayEntity.getmBatch());
			/* ******************************多仓库修改  t  2019-11-05 结束*************************** */
			String status = jsonObject.getString("status");
			
			//----------------------给历史记录表插入数据   start-------------------------------------
			String [] codes = s.split(","); 
			for(String str : codes){
                SimpleDateFormat formatLZ = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String timeLZ = formatLZ.format(new Date());
				BarCodeOperation bar = new BarCodeOperation();
				bar.setOperator(Long.parseLong(binding_person));
				bar.setOperatingTime(timeLZ);
				bar.setBarCode(str);
				bar.setLocationId(location_code);
				bar.setBatch(zcMaterielAndTrayEntity.getmBatch());
				bar.setMaterielId(zcMaterielAndTrayEntity.getMid());
				bar.setType("上架");
				if(!"0".equals(status)){
					bar.setResult("成功");
				}else{
					bar.setResult("失败");
				}
				/* ******************************多仓库修改  t  2019-11-05 开始*************************** */
				//操作记录添加仓库id
				bar.setWarehouse_id(warehouse_id);
				/* ******************************多仓库修改  t  2019-11-05 结束*************************** */
				barCodeOperationService.insert(bar);
			}
			//----------------------给历史记录表插入数据  end-------------------------------------
			
			if("0".equals(status)){
				break;
			}
		}
		
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			logger.info("区域库存的移动(上架)传送数据失败");
			e.printStackTrace();
		}
	}
	/* ******************************多仓库修改  t  2019-11-05 开始*************************** */
	//多仓库修改之前：public JSONObject bindAndUp2SpecialAreaMethod1(HttpServletResponse response,String downType,String materiel_code,String location_code,String tray_code,String targetRegion,String binding_person,Long mid,String mBatch){
	/**
	 * 上架方法
	 * @param response
	 * @param downType 类型
	 * @param materiel_code 条码
	 * @param location_code 库位
	 * @param tray_code 托盘码
	 * @param targetRegion 指定区域
	 * @param binding_person 人员id
	 * @param mid 物料id
	 * @param mBatch 批次
	 * @param warehouse_id 仓库id
	 * @return
	 */
	public JSONObject bindAndUp2SpecialAreaMethod1(HttpServletResponse response,String downType,String materiel_code,String location_code,String tray_code,String targetRegion,String binding_person,Long mid,String mBatch,Long warehouse_id){
		/* ******************************多仓库修改  t  2019-11-05 结束*************************** */
		JSONObject jsonObject = new JSONObject();
		int count=0;
		if("良品区".equals(targetRegion)){
			/* ******************************多仓库修改  t  2019-11-05 开始*************************** */
			//根据库位码和仓库id查询在良品区的条数
			count = zcBindAndUnbindService.selectCountGoodByLocationCode(location_code,warehouse_id);
			//查询库位码是否是良品区的
			//多仓库修改之前：count = zcBindAndUnbindService.selectCountGoodByLocationCode(location_code);
			/* ******************************多仓库修改  t  2019-11-05 结束*************************** */
			if(count==0){
				jsonObject.put("status", "0");
	            jsonObject.put("message", "库位码错误");
	            return jsonObject;
			}
		}else if("不良品区".equals(targetRegion)){
			/* ******************************多仓库修改  t  2019-11-05 开始*************************** */
			//根据库位码和仓库id查询在不良品区的条数
			count = zcBindAndUnbindService.selectCountBadByLocationCode(location_code,warehouse_id);
			//查询库位码是否是不良品区的
			//多仓库修改之前：count = zcBindAndUnbindService.selectCountBadByLocationCode(location_code);
			/* ******************************多仓库修改  t  2019-11-05 结束*************************** */
			if(count==0){
				jsonObject.put("status", "0");
	            jsonObject.put("message", "库位码错误");
	            return jsonObject;
			}
		}
		if(downType==null || "".equals(downType)){
			downType= "2";
		}
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
		if(tray_code==null || "".equals(tray_code)){
			tray_code = System.currentTimeMillis()+"";
		}
		zcMaterielAndTrayEntity.setMateriel_code(materiel_code);
		zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(binding_person));
		zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
		zcMaterielAndTrayEntity.setTargetRegion(targetRegion);
		zcMaterielAndTrayEntity.setTray_code(tray_code);
		zcMaterielAndTrayEntity.setLocation_code(location_code);
		zcMaterielAndTrayEntity.setDownType(Integer.parseInt(downType));
		/* ******************************多仓库修改  t  2019-11-05 开始*************************** */
		//移库
		logger.info("zcBindAndUnbindService区域库存的移动参数：zcMaterielAndTrayEntity="+ zcMaterielAndTrayEntity.toString()
				+ ";warehouse_id="+ warehouse_id);
		int affact = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity,warehouse_id);
		//多仓库修改之前：int affact = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity);
		/* ******************************多仓库修改  t  2019-11-05 结束*************************** */
		
		if(affact<=0){
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败");
            return jsonObject;
        }else{
        	jsonObject.put("status", "1");
            jsonObject.put("message", "");
            jsonObject.put("data", "提交成功");
            return jsonObject;
        }
	}
	/**
	 * 区域库存的移动
	 * @param response
	 * @param downType 下架类型，1全部，2部分
	 * @param materiel_code 物料条码
	 * @param location_code 库位条码
	 * @param tray_code 托盘条码
	 * @param targetRegion 目标区域
	 * @param binding_person 人员id
	 * ******************************多仓库修改  t  2019-11-06 开始*************************** 
	 * @param warehouse_id 仓库id
	 * ******************************多仓库修改  t  2019-11-06 结束***************************
	 */
	@RequestMapping("bindAndUp2SpecialArea")
	public void bindAndUp2SpecialArea(HttpServletResponse response,
			String downType, String materiel_code, String location_code,
			String tray_code, String targetRegion, String binding_person
			/* ******************************多仓库修改  t  2019-11-06 开始*************************** */
			//接收仓库id
			,Long warehouse_id
			/* ******************************多仓库修改  t  2019-11-06 结束*************************** */
			) {
		logger.info("bindAndUnbind/bindAndUp2SpecialArea.do上架操作方法传值：downType=" + downType + ";materiel_code=" + materiel_code
				+ ";location_code=" + location_code + "location_code=" + location_code 
				+ ";tray_code="+ tray_code + ";targetRegion="+ targetRegion
				+ ";binding_person="+ binding_person + ";warehouse_id="+ warehouse_id);
		JSONObject jsonObject = new JSONObject();
		int count=0;
		if("良品区".equals(targetRegion)){
			//查询库位码是否是良品区的
			/* ******************************多仓库修改  t  2019-11-06 开始*************************** */
			//根据库位码和仓库id查询在良品区的条数
			count = zcBindAndUnbindService.selectCountGoodByLocationCode(location_code,warehouse_id);
			//多仓库修改之前：count = zcBindAndUnbindService.selectCountGoodByLocationCode(location_code);
			/* ******************************多仓库修改  t  2019-11-06 结束*************************** */
			if(count==0){
				jsonObject.put("status", "0");
	            jsonObject.put("message", "库位码错误");
	            try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					e.printStackTrace();
				}
	            return;
			}
		}else if("不良品区".equals(targetRegion)){
			//查询库位码是否是不良品区的
			/* ******************************多仓库修改  t  2019-11-06 开始*************************** */
			//根据库位码和仓库id查询在不良品区的条数
			count = zcBindAndUnbindService.selectCountBadByLocationCode(location_code,warehouse_id);
			//多仓库修改之前：count = zcBindAndUnbindService.selectCountBadByLocationCode(location_code);
			/* ******************************多仓库修改  t  2019-11-06 结束*************************** */
			if(count==0){
				jsonObject.put("status", "0");
	            jsonObject.put("message", "库位码错误");
	            try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					e.printStackTrace();
				}
	            return;
			}
		}
		if(downType==null || "".equals(downType)){
			downType= "2";
		}
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
		if(tray_code==null || "".equals(tray_code)){
			tray_code = System.currentTimeMillis()+"";
		}
		zcMaterielAndTrayEntity.setMateriel_code(materiel_code);
		zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(binding_person));
		zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
		zcMaterielAndTrayEntity.setTargetRegion(targetRegion);
		zcMaterielAndTrayEntity.setTray_code(tray_code);
		zcMaterielAndTrayEntity.setLocation_code(location_code);
		zcMaterielAndTrayEntity.setDownType(Integer.parseInt(downType));
		/* ******************************多仓库修改  t  2019-11-06 开始*************************** */
		logger.info("zcBindAndUnbindService区域库存的移动参数：zcMaterielAndTrayEntity="+ zcMaterielAndTrayEntity.toString()
				+ ";warehouse_id="+ warehouse_id);
		//调用server区域库存的移动添加参数仓库id
		int affact = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity,warehouse_id);
		//多仓库修改之前：int affact = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity);
		/* ******************************多仓库修改  t  2019-11-06 结束*************************** */
		
		//----------------------给历史记录表插入数据   start-------------------------------------
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = format.format(new Date());
		BarCodeOperation bar = new BarCodeOperation();
		bar.setOperator(Long.parseLong(binding_person));
		bar.setOperatingTime(time);
		bar.setBarCode(materiel_code);
		bar.setLocationId(location_code);
		if("良品区".equals(targetRegion) || "不良品区".equals(targetRegion)){
			bar.setType("上架");
		}else{
			bar.setType("下架");
		}
		if(affact > 0){
			bar.setResult("成功");
		}else{
			bar.setResult("失败");
		}
		/* ******************************多仓库修改  t  2019-11-07 开始*************************** */
		//条码操作记录set仓库id
		bar.setWarehouse_id(warehouse_id);
		/* ******************************多仓库修改  t  2019-11-07 结束*************************** */
		barCodeOperationService.insert(bar);
		//----------------------给历史记录表插入数据  end-------------------------------------
		
		if(affact<=0){
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败");
        }else{
        	jsonObject.put("status", "1");
            jsonObject.put("message", "");
            jsonObject.put("data", "提交成功");
        }
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			logger.info("上架操作方法传值传送数据失败");
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 区域库存的移动
	 * @param response
	 * @param downType 下架类型，1全部，2部分
	 * @param materiel_code 物料条码
	 * @param location_code 库位条码
	 * @param tray_code 托盘条码
	 * @param targetRegion 目标区域
	 * @param binding_person 人员id
	 * ******************************多仓库修改  t  2019-11-06 开始*************************** 
	 * @param warehouse_id 仓库id
	 * ******************************多仓库修改  t  2019-11-06 结束***************************
	 */
	@RequestMapping("bindAndUp2SpecialArea2Llm")
	public void bindAndUp2SpecialArea2Llm(HttpServletResponse response,
			String downType, String materiel_code, String location_code,
			String tray_code, String targetRegion, String binding_person
			/* ******************************多仓库修改  t  2019-11-06 开始*************************** */
			//接收仓库id
			,Long warehouse_id
			/* ******************************多仓库修改  t  2019-11-06 结束*************************** */
			) {
		logger.info("bindAndUnbind/bindAndUp2SpecialArea2.do区域库存的移动接收参数：downType=" + downType + ";materiel_code=" + materiel_code
				+ ";location_code=" + location_code + "location_code=" + location_code 
				+ ";tray_code="+ tray_code + ";targetRegion="+ targetRegion
				+ ";binding_person="+ binding_person + ";warehouse_id="+ warehouse_id);
		JSONObject jsonObject = new JSONObject();
		downType = "2";
		List<String> listsx = Arrays.asList(materiel_code.split(","));
		List<ZcMaterielAndTrayEntity> list = new ArrayList<>();
		for (String s:listsx){
			/* ******************************多仓库修改  t  2019-11-06 开始*************************** */
			//通过物料条码和仓库id查询物料所在位置 以托盘为主
			ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielTrayLocationByCode(s,warehouse_id);
			//多仓库修改之前：ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielTrayLocationByCode(s);
			/* ******************************多仓库修改  t  2019-11-06 结束*************************** */
			String tray_code1 = zcMaterielAndTrayEntity.getTray_code();
			int fid = 0;
			for (int i = 0; i < list.size(); i++) {
				if(list.get(i).getTray_code().equals(tray_code1)){
					String Materiel_code = list.get(i).getMateriel_code()+","+s;
					zcMaterielAndTrayEntity.setMateriel_code(Materiel_code);
					list.remove(i);
					list.add(zcMaterielAndTrayEntity);
					fid = 1;
					break;
				}
			}
			if(fid == 0){
				zcMaterielAndTrayEntity.setMateriel_code(s);
				list.add(zcMaterielAndTrayEntity);
			}
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = format.format(new Date());
		for (ZcMaterielAndTrayEntity zcMaterielAndTrayEntity:list){
			//location_code = zcMaterielAndTrayEntity.getLocation_code();
			String s = zcMaterielAndTrayEntity.getMateriel_code();
			location_code = zcMaterielAndTrayEntity.getLocation_code();
			/* ******************************多仓库修改  t  2019-11-06 开始*************************** */
			logger.info("区域库存的移动22方法传值：downType=" + downType + ";条码s=" + s
					+ ";location_code=" + location_code + ";time=" + time
					+ "targetRegion=" + targetRegion + ";binding_person="+ binding_person 
					+ ";mid="+ zcMaterielAndTrayEntity.getMid()
					+ ";mBatch="+ zcMaterielAndTrayEntity.getmBatch()
					+ ";warehouse_id="+ warehouse_id);
			jsonObject = bindAndUp2SpecialAreaMethod(response, downType, s,
					location_code, tray_code, targetRegion, binding_person,
					zcMaterielAndTrayEntity.getMid(),
					zcMaterielAndTrayEntity.getmBatch(),warehouse_id);
			//多仓库修改之前：jsonObject = bindAndUp2SpecialAreaMethod( response, downType, s, location_code, tray_code, targetRegion, binding_person,zcMaterielAndTrayEntity.getMid(),zcMaterielAndTrayEntity.getmBatch());
			/* ******************************多仓库修改  t  2019-11-06 结束*************************** */
			String status = jsonObject.getString("status");
			
			//----------------------给历史记录表插入数据   start-------------------------------------
			String [] codes = s.split(",");
			for(String str : codes){
				BarCodeOperation bar = new BarCodeOperation();
				bar.setOperator(Long.parseLong(binding_person));
				bar.setOperatingTime(time);
				bar.setBarCode(str);
				bar.setLocationId(location_code);
				bar.setBatch(zcMaterielAndTrayEntity.getmBatch());
				bar.setMaterielId(zcMaterielAndTrayEntity.getMid());
				bar.setType("下架");
				if(!"0".equals(status)){
					bar.setResult("成功");
				}else{
					bar.setResult("失败");
				}
				/* ******************************多仓库修改  t  2019-11-07 开始*************************** */
				//条码操作记录set仓库id
				bar.setWarehouse_id(warehouse_id);
				/* ******************************多仓库修改  t  2019-11-07 结束*************************** */
				barCodeOperationService.insert(bar);
			}
			//----------------------给历史记录表插入数据  end-------------------------------------
			
			if("0".equals(status)){
				break;
			}
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			logger.info("区域库存的移动传值传送数据失败");
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 区域库存的移动22
	 * @param response
	 * @param downType 下架类型，1全部，2部分
	 * @param materiel_code 物料条码
	 * @param location_code 库位条码
	 * @param tray_code 托盘条码
	 * @param targetRegion 目标区域
	 * @param binding_person 人员id
	 * ******************************多仓库修改  t  2019-11-06 开始*************************** 
	 * @param warehouse_id 仓库id
	 * ******************************多仓库修改  t  2019-11-06 结束***************************
	 */
	public JSONObject bindAndUp2SpecialAreaMethod(HttpServletResponse response,
			String downType, String materiel_code, String location_code,
			String tray_code, String targetRegion, String binding_person,
			Long mid, String mBatch
			/* ******************************多仓库修改  t  2019-11-06 开始*************************** */
			//接收仓库id
			,Long warehouse_id
			/* ******************************多仓库修改  t  2019-11-06 结束*************************** */
			) {
		JSONObject jsonObject = new JSONObject();
		int count=0;
		if("良品区".equals(targetRegion)){
			//查询库位码是否是良品区的
			/* ******************************多仓库修改  t  2019-11-06 开始*************************** */
			//根据库位码和仓库id查询在良品区的条数
			count = zcBindAndUnbindService.selectCountGoodByLocationCode(location_code,warehouse_id);
			//多仓库修改之前：count = zcBindAndUnbindService.selectCountGoodByLocationCode(location_code);
			/* ******************************多仓库修改  t  2019-11-06 结束*************************** */
			if(count==0){
				jsonObject.put("status", "0");
	            jsonObject.put("message", "库位码错误");
	            return jsonObject;
			}
		}else if("不良品区".equals(targetRegion)){
			//查询库位码是否是不良品区的
			/* ******************************多仓库修改  t  2019-11-06 开始*************************** */
			//根据库位码和仓库id查询在不良品区的条数
			count = zcBindAndUnbindService.selectCountBadByLocationCode(location_code,warehouse_id);
			//多仓库修改之前：count = zcBindAndUnbindService.selectCountBadByLocationCode(location_code);
			/* ******************************多仓库修改  t  2019-11-06 结束*************************** */
			if(count==0){
				jsonObject.put("status", "0");
	            jsonObject.put("message", "库位码错误");
	            return jsonObject;
			}
		}
		if(downType==null || "".equals(downType)){
			downType= "2";
		}
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
		if(tray_code==null || "".equals(tray_code)){
			tray_code = System.currentTimeMillis()+"";
		}
		zcMaterielAndTrayEntity.setMateriel_code(materiel_code);
		zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(binding_person));
		zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
		zcMaterielAndTrayEntity.setTargetRegion(targetRegion);
		zcMaterielAndTrayEntity.setTray_code(tray_code);
		zcMaterielAndTrayEntity.setLocation_code(location_code);
		zcMaterielAndTrayEntity.setDownType(Integer.parseInt(downType));
		/* ******************************多仓库修改  t  2019-11-07 开始*************************** */
		//给zcMaterielAndTrayEntity添加warehouse_id
		zcMaterielAndTrayEntity.setWarehouse_id(warehouse_id);
		/* ******************************多仓库修改  t  2019-11-07 结束*************************** */
//		int affact = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity);
		logger.info("soldOut  llm 下架 参数：zcMaterielAndTrayEntity="+ zcMaterielAndTrayEntity.toString());
		int affact = soldOut(zcMaterielAndTrayEntity, warehouse_id);
		if(affact<=0){
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败");
        }else{
        	jsonObject.put("status", "1");
            jsonObject.put("message", "");
            jsonObject.put("data", "提交成功");
        }
		return jsonObject;
	}
	
	/**
	 * llm 下架
	 * @Title:soldOut   
	 * @return
	 */
	public int soldOut(ZcMaterielAndTrayEntity zcMaterielAndTrayEntity, Long warehouse_id){
		int up = 0;
		String [] split = zcMaterielAndTrayEntity.getMateriel_code().split(",");
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity2 = new ZcMaterielAndTrayEntity();
		String tray_code = System.currentTimeMillis()+"";
		//一、、从原来位置下架
		//如果是全部下架
		if(zcMaterielAndTrayEntity.getDownType() == 1){
			//根据库位查询所有托盘
			ZcTrayAndLocationEntity a = new ZcTrayAndLocationEntity();
			a.setLocation_code(zcMaterielAndTrayEntity.getLocation_code());
			/* ******************************多仓库修改  t  2019-11-07 开始*************************** */
			//给zcMaterielAndTrayEntity添加warehouse_id
			a.setWarehouse_id(zcMaterielAndTrayEntity.getWarehouse_id());
			/* ******************************多仓库修改  t  2019-11-07 结束*************************** */
			ZcTrayAndLocationEntity zcTrayAndLocationEntityOld = zcBindAndUnbindService.selectTrayCodeByLocationCode(a);
			if(zcTrayAndLocationEntityOld != null){
				String [] trays = zcTrayAndLocationEntityOld.getTray_code().split(",");
				for(String tray : trays){
					//删除每个托盘
					inventoryService.deleteByCode("tray_code", tray, "zc_materiel_tray");
				}
				/* ******************************多仓库修改  t  2019-11-07 开始*************************** */
				//删除库位
				//根据id删除库位
				inventoryService.deleteByCode("id", zcMaterielAndTrayEntity.getId()+"", "zc_tray_location");
				//多仓库修改之前：inventoryService.deleteByCode("location_code", zcMaterielAndTrayEntity.getLocation_code(), "zc_tray_location");
				/* ******************************多仓库修改  t  2019-11-07 结束*************************** */
			}
			zcMaterielAndTrayEntity2.setTray_code(zcMaterielAndTrayEntity.getTray_code());
			zcMaterielAndTrayEntity2.setMateriel_code(zcMaterielAndTrayEntity.getMateriel_code());
			up = up(tray_code,zcMaterielAndTrayEntity2, split, warehouse_id);
		//如果是部分下架
		}else{
			//根据物料码找托盘信息
			zcMaterielAndTrayEntity2 = ReceiveDetailService.queryMaterielTrayByCode(split[0]);
			/* ******************************多仓库修改  t  2019-11-07 开始*************************** */
			//给zcMaterielAndTrayEntity添加warehouse_id
			zcMaterielAndTrayEntity2.setWarehouse_id(zcMaterielAndTrayEntity.getWarehouse_id());
			/* ******************************多仓库修改  t  2019-11-07 结束*************************** */
			String materiel_code = zcMaterielAndTrayEntity2.getMateriel_code();
			int num = 0;
			for(String materielCode : split){
				//1、用空字符串替换每个条码
				materiel_code = materiel_code.replace(materielCode + ",", "");
				//2、如果替换后物料条码为空，删除这条数据
				if(materiel_code.length() == 0){
					/* ******************************多仓库修改  t  2019-11-07 开始*************************** */
					//删除托盘号加仓库id参数
					deleteMaterielAndTray(zcMaterielAndTrayEntity2.getId(), zcMaterielAndTrayEntity2.getTray_code(),zcMaterielAndTrayEntity.getWarehouse_id());
					//多仓库修改之前：deleteMaterielAndTray(zcMaterielAndTrayEntity2.getId(), zcMaterielAndTrayEntity2.getTray_code());
					/* ******************************多仓库修改  t  2019-11-07 结束*************************** */
				}else{
					//3、修改数据
					inventoryService.updateById(zcMaterielAndTrayEntity2.getId()+"", "materiel_code", materiel_code, "zc_materiel_tray");
					CodeMark ck = cancellingStockDetailService.queryCodeByCode(materielCode);
					if(num == 0){
						num = zcMaterielAndTrayEntity2.getmNum() - ck.getNum();
					}else{
						num = num - ck.getNum();
					}
					if(num > 0){
						inventoryService.updateById(zcMaterielAndTrayEntity2.getId()+"", "mNum", num+"", "zc_materiel_tray");
					}else{
						ReceiveDetailService.deleteMaterielTrayById(zcMaterielAndTrayEntity2.getId());
					}
				}
			}
			//zcMaterielAndTrayEntity2.setMateriel_code(materiel_code+",");
			zcMaterielAndTrayEntity2.setMateriel_code(zcMaterielAndTrayEntity.getMateriel_code());
			logger.info("up  方法 参数：tray_code="+tray_code+";zcMaterielAndTrayEntity2="+ zcMaterielAndTrayEntity2.toString()+";split="+split);
			up = up(tray_code,zcMaterielAndTrayEntity2, split, warehouse_id);
		}
		return up;
	}
	
	
	public int up(String tray_code,ZcMaterielAndTrayEntity zcMaterielAndTrayEntity, String[] split, Long warehouse_id){
		int i = 0;
		//二、在缓存区上架
		//1、在物料和托盘关系表新增记录
		int sum = 0;
		for (String codeMark2 : split) {
			CodeMark ck = cancellingStockDetailService.queryCodeByCode(codeMark2);
			sum += ck.getNum();
		}
		
		zcMaterielAndTrayEntity.setMateriel_code(zcMaterielAndTrayEntity.getMateriel_code()+",");
		zcMaterielAndTrayEntity.setmNum(sum);
		zcMaterielAndTrayEntity.setTray_code(tray_code);
		i = inventoryService.MaterielTrayInsert(zcMaterielAndTrayEntity);
		ZcMaterileMoveInfoEntity zcMaterileMoveInfoEntity = new ZcMaterileMoveInfoEntity();
		zcMaterileMoveInfoEntity.setMid(zcMaterielAndTrayEntity.getMid());
		zcMaterileMoveInfoEntity.setNum(zcMaterielAndTrayEntity.getmNum());
		zcMaterileMoveInfoEntity.setPici(zcMaterielAndTrayEntity.getmBatch());
		zcMaterileMoveInfoEntity.setEnterPerson(zcMaterielAndTrayEntity.getBinding_person());
		zcMaterileMoveInfoEntity.setEnterDate(DateUtil.dateFormat3());
		zcMaterileMoveInfoEntity.setWarehouse_id(warehouse_id);
		
		//记录下架记录
		for (String codeMark2 : split) {
			ZcMaterielAndTrayEntity zcMaterielAndTrayEntity1 = zcMaterielAndTrayEntity;
			zcMaterielAndTrayEntity1 .setMateriel_code(codeMark2);
			zcBindAndUnbindService.insertUnbindleRecord(zcMaterielAndTrayEntity1);
		}
		//缓存区添加库存
		int inCache = zcBindAndUnbindService.inCache(zcMaterileMoveInfoEntity);
		logger.info("inCache缓冲区添加数据：zcMaterileMoveInfoEntity="+zcMaterileMoveInfoEntity.toString()+"返回"+inCache);
		int outGood = zcBindAndUnbindService.outGood(zcMaterileMoveInfoEntity);
		logger.info("outGood从良品库出库：zcMaterileMoveInfoEntity="+zcMaterileMoveInfoEntity.toString()+"返回"+inCache);
		//2、根据缓存区库位查询数据
		ZcTrayAndLocationEntity a = new ZcTrayAndLocationEntity();	
		a.setLocation_code("HC");
		/* ******************************多仓库修改  t  2019-11-07 开始*************************** */
		//给zcMaterielAndTrayEntity添加warehouse_id
		a.setWarehouse_id(zcMaterielAndTrayEntity.getWarehouse_id());
		/* ******************************多仓库修改  t  2019-11-07 结束*************************** */
		ZcTrayAndLocationEntity zcTrayAndLocationEntityOld = zcBindAndUnbindService.selectTrayCodeByLocationCode(a);
		//3、如果不为空，修改数据
		if(zcTrayAndLocationEntityOld != null){
			String trayCodes = zcTrayAndLocationEntityOld.getTray_code() + zcMaterielAndTrayEntity.getTray_code() + ",";
			inventoryService.updateById(zcTrayAndLocationEntityOld.getId()+"", "tray_code", trayCodes, "zc_tray_location");
		}else{
			//4、新增库位
			ZcTrayAndLocationEntity zcTrayAndLocationEntity = new ZcTrayAndLocationEntity();
			//托盘码
			zcTrayAndLocationEntity.setTray_code(tray_code);
			//库区编码
			zcTrayAndLocationEntity.setLocation_code("HC");
			//绑定人
			zcTrayAndLocationEntity.setBinding_person(zcMaterielAndTrayEntity.getBinding_person());
    		//绑定时间
			zcTrayAndLocationEntity.setBinding_date(zcMaterielAndTrayEntity.getBinding_date());
			/* ******************************多仓库修改  t  2019-11-07 开始*************************** */
			//给zcTrayAndLocationEntity添加warehouse_id
			zcTrayAndLocationEntity.setWarehouse_id(zcMaterielAndTrayEntity.getWarehouse_id());
			/* ******************************多仓库修改  t  2019-11-07 结束*************************** */
			 i = inventoryService.trayLocationInsert(zcTrayAndLocationEntity);
			 logger.info("trayLocationInsert在托盘-库位绑定表中新增一条记录：zcMaterileMoveInfoEntity="+zcMaterileMoveInfoEntity.toString()+"返回"+i);
		}
		return i;
	}
	/**
	 * 删除托盘号
	 * @param id
	 * @param trayCode
	 */
	public void deleteMaterielAndTray(Long id, String trayCode
			/* ******************************多仓库修改  t  2019-11-07 开始*************************** */
			//删除托盘号接收参数仓库id
			,Long warehouse_id
			/* ******************************多仓库修改  t  2019-11-07 结束*************************** */
			){
		//1、删除这个记录
		ReceiveDetailService.deleteMaterielTrayById(id);
		//2、根据托盘号查询库位数据信息
		ZcTrayAndLocationEntity queryTrayLocationByTray = ReceiveDetailService.queryTrayLocationByTray(trayCode);
		//3、把托盘号用“”代替
		String trays = queryTrayLocationByTray.getTray_code().replace(trayCode+",", "");
		//4、如果替换后托盘码字符串为空，删除这条记录
		if(trays.length() == 0){
			inventoryService.deleteById(queryTrayLocationByTray.getId()+"", "zc_tray_location");
		}else{
			//5、否则修改数据
			inventoryService.updateById(queryTrayLocationByTray.getId()+"", "tray_code", trays, "zc_tray_location");
		}
	}
	
	//---------------------------------------------------------jyy上架代码重写2019-12-05start---------------------------------------------------------
	
	/**
	 * 上架前根据条码查询此条码所在托盘的所有条码，并校验此条码当前进行到了哪个环节，数据是否正确等
	 * @author jyy
	 * @param warehouse_id 仓库id
	 * @param materiel_code 物料条码
	 * @param response  响应
	 */
	@RequestMapping("/selectMaterielInfoByCodeApp")
	public void selectMaterielInfoByCodeApp(Long warehouse_id, String materiel_code, HttpServletResponse response){
		logger.info("bindAndUnbind/selectMaterielInfoByCodeApp.do（上架）根据物料条码查询物料信息接收参数：warehouse_id="
				+ warehouse_id + ",materiel_code=" + materiel_code);
		JSONObject jsonObject = new JSONObject();
		StringBuffer buffer = new StringBuffer();
		
		try {
			//根据条码查询此条码所在托盘的信息
			List<TrayLocation> trayLocations = zcBindAndUnbindService.selectInfoByCode(materiel_code);
			
			if(trayLocations.size() > 1){
				//说明：codeMark表存在两个一样的条码  or 一个条码在两个托盘及库位上--数据错误--此条码数据错误，请联系管理员
				jsonObject.put("status", "0");
				jsonObject.put("message", "有重复条码，数据错误，请联系管理员");
			} else if(trayLocations.size() == 1){
				TrayLocation trayLocation = trayLocations.get(0);
				if(trayLocation.getWarehouse_id() != null) {
					if(warehouse_id.equals(trayLocation.getWarehouse_id())) {
						if( trayLocation.getLocation_code()!= null && !"".equals(trayLocation.getLocation_code()) ) {
							if(!"SY".equals(trayLocation.getLocation_code())) {
								//不在损溢区
								if( "HC".equals(trayLocation.getLocation_code()) || "DJ".equals(trayLocation.getLocation_code()) ) {
									//数据在待检区或缓存区，查询此条码有没有质检
									Integer i = barCodeOperationService.queryStatusByCode(materiel_code);
									if(i == 0){
										jsonObject.put("status", "0");
										jsonObject.put("message", "此条码未质检");
									}else {
										//数据没问题，返回此托盘所有条码信息 ：
										//1.查推荐库位
										if(trayLocation.getIs_ng() == 0) {
											if( trayLocation.getRegion_id() != null && !"".equals(trayLocation.getRegion_id()) ) {
												String location = zcBindAndUnbindService.selectTopOneLocation(trayLocation.getRegion_id());
												trayLocation.setBetter_location(location);
											}else {//此物料没有绑定库区，没有推荐库位
												trayLocation.setBetter_location("");
											}
										}else {//不良品
											trayLocation.setBetter_location("不良品区");
										}
										//2.查询同批剩余
										int tcount = zcBindAndUnbindService.selectOtherCommon(trayLocation);
										trayLocation.setTcount(tcount);
										
										String[] codes = trayLocation.getMateriel_code().split(",");
										for (String s : codes) {
											//3.根据条码在codemark表中查询此条码的信息
											Integer codeNum =  zcBindAndUnbindService.queryCodeMarkByCode(s);
											if(buffer.length() == 0) {
												buffer.append(codeNum);
											}else {
												buffer.append(",");
												buffer.append(codeNum);
											}
										}
										trayLocation.setNums(buffer.toString());
										//4.给app传值
										jsonObject.put("status", "1");
										jsonObject.put("data",trayLocation);
										buffer = null;
									}
								}else {//已上架，在库位上
									jsonObject.put("status", "0");
									jsonObject.put("message", "此条码已上架");
								}
							}else {//在损益区
								jsonObject.put("status", "0");
								jsonObject.put("message", "此条码在损益区");
							}
						}else {//条码所在库位为空
							jsonObject.put("status", "0");
							jsonObject.put("message", "此条码没有所属库位，数据错误，请联系管理员");
						}
					}else {//仓库id不匹配
						jsonObject.put("status", "0");
						jsonObject.put("message", "此条码不属于当前登录仓库");
					}
				}else {//此条码所在仓库为空（基本不会存在）
					jsonObject.put("status", "0");
					jsonObject.put("message", "此条码没有所属仓库，数据错误，请联系管理员");
				}
			} else {//查询数据为空，此条码不在托盘及库位上，可能没收货或已出库或已拆箱
				//根据条码查询操作记录表中的最后一条记录
				BarCodeOperation param = new BarCodeOperation();
				param.setBarCode(materiel_code);
				param.setWarehouse_id(warehouse_id);
				//根据条码和仓库id和条码在操作记录表中查询此条码,存在，条码已出库，不存在，条码在别的仓库
				List<BarCodeOperation> list = barCodeOperationService.queryAllByMution(param);
				
				if(list.size() > 0) {//此条码已出库或已拆箱
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "条码已出库或已拆箱");
					jsonObject.put("data", null);
				}else {//操作记录中没有
					//根据条码，在receivemark表中查询
					ReceiveMark receiveMark = ReceiveDetailService.selectReceiveMarkByCode(materiel_code);
					
					if(receiveMark != null) {
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "条码未收货，收货单号："+receiveMark.getReceiveDetail().getReceiveNumber());
						jsonObject.put("data", null);
					}else {
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "系统无此条码");
						jsonObject.put("data", null);
					}
				}
			}
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			jsonObject.put("status", "0");
			jsonObject.put("message", "上架查询条码信息方法异常");
			jsonObject.put("data", null);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			logger.error("上架查询条码信息方法异常");	
			e.printStackTrace();
		}
	}
	
	/**
	 * 上架库位校验
	 * 上架APP扫描库位，后台校验此库位是否存在，以及是良品区的库位还是不良品区的库位
	 * @author jyy
	 * @param warehouse_id 仓库id
	 * @param location 库位编号
	 * @param response 响应
	 */
	@RequestMapping("/selectLocationExist")
	public void selectLocationExist(String warehouse_id, String location, HttpServletResponse response) {
		logger.info("bindAndUnbind/selectLocationExist.do（上架，库位校验）接收参数：warehouse_id="
				+ warehouse_id + ",location=" + location);
		JSONObject jsonObject = new JSONObject();
		
		try {
			//去查询，返回库区名称，对库区名称进行判断
			String region_name = zcBindAndUnbindService.selectLocationExist(warehouse_id, location);
			
			if(region_name != null && !"".equals(region_name) ) {
				
				//判断此库位是不是不良品区
				if("不良品区".equals(region_name)) {
					//是：返回库区名称“不良品区”
					jsonObject.put("status", "1");
					jsonObject.put("data",region_name);
				}else {
					//否：返回库位码
					jsonObject.put("status", "1");
					jsonObject.put("data",location);
				}
			}else {
				//传递数据到页面
				jsonObject.put("status", "0");
				jsonObject.put("message", "库位码错误");
				jsonObject.put("data", null);
			}
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			jsonObject.put("status", "0");
			jsonObject.put("message", "库位校验方法异常");
			jsonObject.put("data", null);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			logger.error("上架：库位校验方法异常");	
			e.printStackTrace();
		}
	}
	
	/**
	 * 上架提交
	 * @param response 响应
	 * @param materiel_code 物料条码
	 * @param delete_code 被删除的，不上架的物料
	 * @param targetLocation 目标区域
	 * @param binding_person 人员id
	 * @param warehouse_id 仓库id
	 * @param is_full 0完整托盘  1不完整 
	 * @param mid 物料id
	 * @param mbatch 批次
	 */
	@RequestMapping("bindAndUp2SpecialArea3")
	public void bindAndUp2SpecialArea3(HttpServletResponse response, String materiel_code, String delete_code,
			String targetLocation, Long binding_person, Long warehouse_id, Integer is_full, Long mid, String mbatch) {
		
		logger.info("bindAndUnbind/bindAndUp2SpecialArea3.do上架操作方法传值：materiel_code=" + materiel_code + ";location_code="
				+ ";targetLocation="+ targetLocation+ ";binding_person="+ binding_person + ";warehouse_id="+ warehouse_id+ ";is_full="+ is_full
				+ ";mid="+ mid+ ";mbatch="+ mbatch + ";delete_code="+ delete_code);
		JSONObject jsonObject = new JSONObject();
		int affact = 0;
		try {
			
			if(is_full == 0) {//完整托盘
				affact = zcBindAndUnbindService.wholeUp( materiel_code, mid, mbatch, targetLocation,  binding_person,  warehouse_id);
			}else {//不完整托盘，部分上架
				affact = zcBindAndUnbindService.partUp(materiel_code, mid, mbatch, targetLocation,  binding_person,  warehouse_id, delete_code);
			}
			
			if(affact > 0) {
				jsonObject.put("status", "1");
				jsonObject.put("message", "");
				jsonObject.put("data","上架成功");
			}else if(affact == -1) {
				jsonObject.put("status", "0");
				jsonObject.put("message", "接收参数为空");
				jsonObject.put("data", null);
			}else if(affact == -2) {
				jsonObject.put("status", "0");
				jsonObject.put("message", "解析后参数为空");
				jsonObject.put("data", null);
			}else if(affact == -3) {
				jsonObject.put("status", "0");
				jsonObject.put("message", "库位为空");
				jsonObject.put("data", null);
			}else if(affact == -4) {
				jsonObject.put("status", "0");
				jsonObject.put("message", "托盘为空");
				jsonObject.put("data", null);
			}else if(affact == -5) {
				jsonObject.put("status", "0");
				jsonObject.put("message", "条码为空");
				jsonObject.put("data", null);
			}else if(affact == -6) {
				jsonObject.put("status", "0");
				jsonObject.put("message", "已上架，请勿重复操作");
				jsonObject.put("data", null);
			}else if(affact == -7) {
				jsonObject.put("status", "0");
				jsonObject.put("message", "当前托盘数据已发生变化，请核对");
				jsonObject.put("data", null);
			}else if(affact == -8) {
				jsonObject.put("status", "0");
				jsonObject.put("message", "当前托盘数据在损溢区");
				jsonObject.put("data", null);
			}else if(affact == -9) {
				jsonObject.put("status", "0");
				jsonObject.put("message", "数据错误请核对");
				jsonObject.put("data", null);
			}else {
				jsonObject.put("status", "0");
				jsonObject.put("message", "上架失败");
				jsonObject.put("data", null);
			}
			
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			jsonObject.put("status", "0");
			jsonObject.put("message", "上架错误");
			jsonObject.put("data", null);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			logger.error("上架：提交方法异常");	
			e.printStackTrace();
		}
		
		//上架提交成功后，删除所有没用的托盘，和空托盘，空库位
		zcBindAndUnbindService.deleteTrayAndLocation();
	
	}
	
	/**
	 * 下架
	 * @param response
	 * @param downType 下架类型，1全部，2部分
	 * @param materiel_code 物料条码:","号拼接的字符串
	 * @param location_code 库位条码
	 * @param targetRegion 目标区域,默认值：HC
	 * @param binding_person 人员id
	 * @param warehouse_id 仓库id
	 */
	@RequestMapping("bindAndUp2SpecialArea2")
	public void bindAndUp2SpecialArea2(HttpServletResponse response,
			String downType, String materiel_code, String location_code,
			String targetRegion, Long binding_person,Long warehouse_id) {
		
		logger.info("bindAndUnbind/bindAndUp2SpecialArea2.do区域库存的移动接收参数：downType=" + downType + ";materiel_code=" + materiel_code
				+ ";location_code=" + location_code + "location_code=" + location_code 
				+ ";targetRegion="+ targetRegion
				+ ";binding_person="+ binding_person + ";warehouse_id="+ warehouse_id);
		
		JSONObject jsonObject = new JSONObject();
		int affact = 0;
		StringBuffer erro = new StringBuffer();
		StringBuffer out = new StringBuffer();
		StringBuffer dow = new StringBuffer();
		StringBuffer num = new StringBuffer();
		
		try {
			
			if( location_code != null && !"".equals(location_code) ) {
				if( materiel_code != null && !"".equals(materiel_code) ) {
					if("1".equals(downType)) { 
						//全部下架
						affact = zcBindAndUnbindService.wholeDown(location_code, binding_person, warehouse_id);
					}else {
						String[] codes = materiel_code.split(",");
						for (String s: codes) {
							//根据条码查询此条码所在托盘的信息
							List<TrayLocation> trayLocations = zcBindAndUnbindService.selectInfoByCode(s);
							if(trayLocations.size() > 0) {
								if(trayLocations.size() < 2) {
									
									TrayLocation trayLocation = trayLocations.get(0);
									
									if( !"HC".equals(trayLocation.getLocation_code()) ) {
										//查询条码数量
										Integer codeNum =  zcBindAndUnbindService.queryCodeMarkByCode(s);
										
										if(codeNum != null && !"".equals(codeNum)) {
											//部分下架
											affact = zcBindAndUnbindService.partDown(s, codeNum, trayLocation, binding_person);
										}else {
											//
											affact = -6;
											num.append(s+",");
											break;
										}
									}else {
										//已下架
										affact = -5;
										dow.append(s+",");
										break;
									}
								}else {
									//有重复数据，数据错误
									affact = -4;
									erro.append(s+",");
									break;
								}
							}else {
								//条码已出库或已拆箱
								affact = -3;
								out.append(s+",");
								break;
							}
						}//for循环结束
					}
				}else {
					affact = -2;
				}
			}else {
				affact = -1;
			}
			
			if(affact > 0) {
				jsonObject.put("status", "1");
				jsonObject.put("message", "");
				jsonObject.put("data","下架成功");
			}else if(affact == -1) {
				jsonObject.put("status", "0");
				jsonObject.put("message", "库位为空");
				jsonObject.put("data", null);
			}else if(affact == -2) {
				jsonObject.put("status", "0");
				jsonObject.put("message", "条码为空");
				jsonObject.put("data", null);
			}else if(affact == -3) {
				jsonObject.put("status", "0");
				jsonObject.put("message", "条码"+out.toString()+"已出库或已拆箱 ");
				jsonObject.put("data", null);
			}else if(affact == -4) {
				jsonObject.put("status", "0");
				jsonObject.put("message", "条码："+erro.toString()+"有重复数据，数据错误 ");
				jsonObject.put("data", null);
			}else if(affact == -5) {
				jsonObject.put("status", "0");
				jsonObject.put("message", "条码"+dow.toString()+"已下架，请勿重复操作 ");
				jsonObject.put("data", null);
			}else if(affact == -6) {
				jsonObject.put("status", "0");
				jsonObject.put("message", "条码"+num.toString()+"数量获取错误，请核实");
				jsonObject.put("data", null);
			}else if(affact == -7) {
				jsonObject.put("status", "0");
				jsonObject.put("message", "此库位条码已下架，请勿重复操作 ");
				jsonObject.put("data", null);
			}else {
				jsonObject.put("status", "0");
				jsonObject.put("message", "下架失败");
				jsonObject.put("data", null);
			}
		
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			jsonObject.put("status", "0");
			jsonObject.put("message", "下架出错");
			jsonObject.put("data", null);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
		
	}
	
	
	/**
	 * 通过物料条码和仓库id查询物料所在位置(下架)
	 * @param materiel_code 条码
	 * @param warehouse_id 仓库id
	 * @param response
	 */
	@RequestMapping("selectMaterielLocationByCodeAppDown")
	public void selectMaterielLocationByCodeAppDown(String materiel_code,Long warehouse_id,HttpServletResponse response){
		//日志
		logger.info("bindAndUnbind/selectMaterielLocationByCodeAppDown.do（下架）"
				+ "根据物料条码和仓库id查询物料所在位置接收参数：materiel_code="+materiel_code+",warehouse_id="+warehouse_id);
		
		JSONObject jsonObject = new JSONObject();
		List<String> buffer = new ArrayList<>();
		
		int num = 0;
		
		try {
			//根据条码查询此条码所在托盘的信息
			List<TrayLocation> trayLocations = zcBindAndUnbindService.selectInfoByCode(materiel_code);
			
			if(trayLocations.size() > 1){
				//说明：codeMark表存在两个一样的条码  or 一个条码在两个托盘及库位上--数据错误--此条码数据错误，请联系管理员
				jsonObject.put("status", "0");
				jsonObject.put("message", "有重复条码，数据错误，请联系管理员");
			} else if(trayLocations.size() == 1){
				TrayLocation trayLocation = trayLocations.get(0);
				if(trayLocation.getWarehouse_id() != null) {
					if(warehouse_id.equals(trayLocation.getWarehouse_id())) {
						if( trayLocation.getLocation_code()!= null && !"".equals(trayLocation.getLocation_code()) ) {
							if(!"SY".equals(trayLocation.getLocation_code())) {
								//不在损溢区
								if( !"HC".equals(trayLocation.getLocation_code()) ) {
									if(!"DJ".equals(trayLocation.getLocation_code())) {
										//数据没问题，返回此托盘所有条码信息 ：
										ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
										
										//查询条码数量
										Integer codeNum =  zcBindAndUnbindService.queryCodeMarkByCode(materiel_code);
										//根据库位，查询此库位所有条码信息
										List<BarCodeOperation> list = zcBindAndUnbindService.selectAllCodeByLocation(trayLocation.getLocation_code(), warehouse_id);
										
										//遍历，数量累加，并将所有mid去重，存入集合
										for (BarCodeOperation b : list) {
											num += b.getCodeNum();
											
											if( buffer.indexOf(b.getMaterielId()+"") == -1) {
												buffer.add(b.getMaterielId()+"");
											}
										}
										
										if(buffer.size() > 1) {
											//此库位有多种物料
											zcMaterielAndTrayEntity.setLocation_type("1");
										}else {
											//此库位只有一种物料
											zcMaterielAndTrayEntity.setLocation_type("0");
										}
										
										//扫描条码的数量
										zcMaterielAndTrayEntity.setDown_code_num(codeNum);
										//库位
										zcMaterielAndTrayEntity.setLocation_code(trayLocation.getLocation_code());
										//库位上所有物料的数量
										zcMaterielAndTrayEntity.setLocation_count(num);
										//原接口是库位上所有条码拼接的字符串，当前接口不需要，影响性能，也没什么用
										zcMaterielAndTrayEntity.setMateriel_code(materiel_code);
										//当前扫描的条码
										zcMaterielAndTrayEntity.setMateriel_code_single(materiel_code);
										zcMaterielAndTrayEntity.setCode_num(list.size());
										
										jsonObject.put("status", "1");
										jsonObject.put("data",zcMaterielAndTrayEntity );
									}else {//在待上架区
										jsonObject.put("status", "0");
										jsonObject.put("message", "此条码在待上架区");
									}
								}else {//已下架
									jsonObject.put("status", "0");
									jsonObject.put("message", "此条码已下架");
								}
							}else {//在损益区
								jsonObject.put("status", "0");
								jsonObject.put("message", "此条码在损益区");
							}
						}else {//条码所在库位为空
							jsonObject.put("status", "0");
							jsonObject.put("message", "此条码没有所属库位，数据错误，请联系管理员");
						}
					}else {//仓库id不匹配
						jsonObject.put("status", "0");
						jsonObject.put("message", "此条码不属于当前登录仓库");
					}
				}else {//此条码所在仓库为空（基本不会存在）
					jsonObject.put("status", "0");
					jsonObject.put("message", "此条码没有所属仓库，数据错误，请联系管理员");
				}
			} else {//查询数据为空，此条码不在托盘及库位上，可能没收货或已出库或已拆箱
				//根据条码查询操作记录表中的最后一条记录
				BarCodeOperation param = new BarCodeOperation();
				param.setBarCode(materiel_code);
				param.setWarehouse_id(warehouse_id);
				//根据条码和仓库id和条码在操作记录表中查询此条码,存在，条码已出库，不存在，条码在别的仓库
				List<BarCodeOperation> list = barCodeOperationService.queryAllByMution(param);
				
				if(list.size() > 0) {//此条码已出库或已拆箱
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "条码已出库或已拆箱");
					jsonObject.put("data", null);
				}else {//操作记录中没有
					//根据条码，在receivemark表中查询
					ReceiveMark receiveMark = ReceiveDetailService.selectReceiveMarkByCode(materiel_code);
					
					if(receiveMark != null) {
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "条码未收货，收货单号："+receiveMark.getReceiveDetail().getReceiveNumber());
						jsonObject.put("data", null);
					}else {
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "系统无此条码");
						jsonObject.put("data", null);
					}
				}
			}
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			jsonObject.put("status", "0");
			jsonObject.put("message", "下架查询条码信息方法异常");
			jsonObject.put("data", null);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			logger.error("下架查询条码信息方法异常");	
			e.printStackTrace();
		}
	}
	
	
	//---------------------------------------------------------jyy上架代码重写2019-12-05end-----------------------------------------------------------
}
